﻿using System;
using System.IO;
using System.Threading;

namespace Duo1JHttpServer.Framework.Utils
{
    public static class IOUtils
    {
        /// <summary>
        /// 文件全部读取大小阈值，10MB
        /// </summary>
        private const long OneStepReadMaxSize = 1024 * 1024 * 10;

        /// <summary>
        /// 从流中读取一行
        /// </summary>
        /// <param name="inputStream">输入流</param>
        /// <returns>读到的单行数据</returns>
        public static string StreamReadLine(Stream inputStream)
        {
            int nextChar;
            string resStr = "";
            while (true)
            {
                nextChar = inputStream.ReadByte();
                if (nextChar == '\n')
                {
                    break;
                }

                if (nextChar == '\r')
                {
                    continue;
                }

                if (nextChar == -1)
                {
                    Thread.Sleep(1);
                    continue;
                }

                resStr += Convert.ToChar(nextChar);
            }

            return "".Equals(resStr) ? null : resStr;
        }

        /// <summary>
        /// 读取文件所有内容，限制大小10MB
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static byte[] ReadFileAll(string path)
        {
            if (File.Exists(path))
            {
                try
                {
                    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        if (fs.Length > OneStepReadMaxSize)
                        {
                            ConsoleUtils.WriteRedLine($"File size exceeds the max limit: {fs.Name}");
                            return null;
                        }

                        byte[] res = new byte[fs.Length];
                        fs.Read(res, 0, res.Length);
                        return res;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            ConsoleUtils.WriteRedLine($"Can`t find file: {path}");
            return null;
        }
    }
}